const mysql = require('mysql')
const configMYSQL = require('./config').MYSQL
class DB {
  // 单例 解决多次实例化
  static getInstance () {
    if (!DB.instance) {
      DB.instance = new DB()
    }
    return DB.instance
  }

  // 实例化后就创建SDK api
  constructor () {
    this.connection = null
    this.conn()
  }

  conn () {
    let _this = this
    return new Promise((resolve, reject) => {
      if (!_this.connection) {
        _this.connection = mysql.createConnection({
          host: configMYSQL.HOST,
          user: configMYSQL.USER,
          database: configMYSQL.DATABASE,
          password: configMYSQL.PASS
        })
        _this.connection.connect((err) => {
          if (err) {
            _this = null
            console.log('mysql error')
            reject(err)
          } else {
            console.log('mysql start')
            resolve(_this.connection)
          }
        })
      } else {
        resolve(_this.connection)
      }
    })
  }

  query (params) {
    return new Promise((resolve, reject) => {
      this.connection.query(params, (err, res, fields) => {
        if (err) {
          reject(err)
        } else {
          resolve(res)
        }
      })
    })
  }
}

module.exports = DB.getInstance()
